package com.icesoft.base.manager.config.register;

import cn.hutool.core.io.IoUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.icesoft.base.manager.entity.security.SysMenu;
import com.icesoft.base.manager.model.MenuVo;
import com.icesoft.base.manager.service.security.SysMenuService;
import com.icesoft.core.common.util.JsonUtil;
import com.icesoft.core.web.helper.PathUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

@Component
@AllArgsConstructor
@Slf4j
public class MenuRegister implements ApplicationRunner {
    private SysMenuService sysMenuService;

    @Override
    public void run(ApplicationArguments args) {
        if (sysMenuService.countAll() > 0) {
            return;
        }
        checkCreateMenu();
    }

    public int checkCreateMenu() {
        String json;
        try {
            json = IoUtil.readUtf8(PathUtil.getPathInputStream("config/menu.json"));
        } catch (IOException e) {
            log.error("菜单文件读取失败", e);
            return 0;
        }
        List<MenuVo> menus = JsonUtil.toObject(json, new TypeReference<List<MenuVo>>() {
        });
        if (menus == null) {
            return 0;
        }
        Queue<MenuVo> queue = new LinkedList<>();
        queue.addAll(menus);
        int count = 0;
        while (!queue.isEmpty()) {
            MenuVo menuVo = queue.poll();
            SysMenu sysMenu = sysMenuService.findMenuByPidAndTitle(menuVo.getPid(), menuVo.getTitle());
            if (sysMenu == null) {
                sysMenu = new SysMenu(menuVo);
                sysMenuService.create(sysMenu);
                count++;
            }
            if (menuVo.getChildren() != null) {
                for (MenuVo child : menuVo.getChildren()) {
                    child.setPid(sysMenu.getId());
                }
                queue.addAll(menuVo.getChildren());
            }
        }
        return count;
    }
}
